package cn.springmvc.noconfig.controller;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Objects;
import java.util.Random;

/**
 * ClassName: PushController
 * Desc:  服务端主动推动控制器
 * Date： 2017/5/4
 * Created：shaom
 */
@Controller
public class PushController {

    /**
     * SSE 推送技术,前端会轮询访问这个方法
     * text/event-stream 是 SSE的支持
     *
     * @return
     * @throws InterruptedException
     */
    @RequestMapping(value = "sse", produces = "text/event-stream")
    @ResponseBody
    public String sse() throws InterruptedException {
        Random random = new Random();
        Thread.sleep(5000);
        return "sse " + random.nextInt();
    }


    DeferredResult<String> deferredResult;

    /**
     * servlet3.0的异步方法支持
     *
     * @return
     */
    @RequestMapping(value = "service")
    @ResponseBody
    public DeferredResult<String> service() {
        deferredResult = new DeferredResult<>();
        return deferredResult;
    }

    // 放到service中
    @Scheduled(fixedDelay = 10000)
    public void getAsyncData() {
        System.out.println("执行~~~ Scheduled ~~~");
        if (Objects.nonNull(deferredResult)) {
            deferredResult.setResult(String.valueOf(System.currentTimeMillis()));
        }
    }
}
